# koa2 原生路由实现
# 简单例子
const Koa = require('koa')
const app = new Koa()
app.use( async ( ctx ) => {
let url = ctx.request.url
ctx.body = url
})
app.listen(3000)
@前端进阶之旅: 代码已经复制到剪贴板
访问 http://localhost:3000/hello/world 页面会输出 /hello/world,也就是说上下文的请求request对象中url之就是当前访问的路径名称,可以根据ctx.request.url 通过一定的判断或者正则匹配就可以定制出所需要的路由。
# 定制化的路由
demo源码
https://github.com/poetries/daily-code-practice/tree/master/node/koa/koa2-demo/route-simple
# 源码文件目录
.
├── index.js
├── package.json
└── view
├── 404.html
├── index.html
└── todo.html
@前端进阶之旅: 代码已经复制到剪贴板
# demo源码
const Koa = require('koa')
const fs = require('fs')
const app = new Koa()
/**
* 用Promise封装异步读取文件方法
* @param {string} page html文件名称
* @return {promise}
*/
function render( page ) {
return new Promise(( resolve, reject ) =>